package gov.mogaha.ntis.cmm.mob;

import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServlet;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServletHandler;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServlet.DataSet;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServletHandler.HttpResult;
import gov.mogaha.ntis.cmm.mob.util.Toaster;
import gov.mogaha.ntis.cmm.mob.view.AddressDistrictListView;
import gov.mogaha.ntis.cmm.mob.view.ButtonView;
import gov.mogaha.ntis.cmm.mob.view.EditTextView;
import gov.mogaha.ntis.cmm.mob.view.NewAddressDistrictListView;
import gov.mogaha.ntis.cmm.mob.view.TextAlignView;
import gov.mogaha.ntis.cmm.mob.view.TitleView;

import java.util.ArrayList;
import java.util.Hashtable;

import wire.proto.Binding;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class CmmMobNewAddrInsert extends Activity implements android.widget.RadioGroup.OnCheckedChangeListener, OnClickListener {
	
	public final static boolean INPUT_YN = false; 
	//주소 개체
	/** 주소 개체 */
	Address addressNew;
	String[] cggServlet = {	"mobile/RTP_MOB_CMM", 
							"mobCmm", 
							"selectListCggAddr"};
	String[] umdServlet = { "mobile/RTP_MOB_CMM", 
							"mobCmm", 
							"selectListStreetAddr"};
	
//	ArrayList<String> arrSi = new ArrayList<String>();
	ArrayList<ArrayList<String>> itemsSi = new ArrayList<ArrayList<String>>();
	ArrayList<ArrayList<String>> itemsInitial = new ArrayList<ArrayList<String>>();
//	ArrayAdapter<String> adapterSi;
	ArrayList<Hashtable<String, String>> tmpSi;
	ArrayList<Hashtable<String, String>> tmpUmd;
	Hashtable<String, String> sidoData;
	Hashtable<String, String> umdData;
	/**<B>String ADDR_OVERALL</B><BR>
	 * 주소검색 및 건물번호 등 사용자 입력으로 인해 현재 단계까지 생성된 주소 문자열*/
	String mAddrOverAll = "";
	
	
	//타이틀뷰
	TitleView titleView;
	
	
	//시군구
	String hiddenSi;
	String hiddenGu;
	
//	Spinner spinSi;
	EditText editSi;
	Button btnSiFind;
	
	AddressDistrictListView listDist;
	
	
	//도로명 - 검색 타입
	RadioGroup btnKeywordGroup;
	
	//검색 항목
	Spinner spinInitials;
	TextAlignView textKeywordType;
	ButtonView btnKeywordInitial;
	EditTextView editRoadname;
	Button btnKeywordFind;
	boolean initialSelected = false;
	
	NewAddressDistrictListView listDistForNewAddr;
	EditText editFullAddress;
	
	/**<B>boolean isFindButtonClicked</B><BR>
	 * 초성검색 혹은 명칭검색을 실행한 이력이 있는지를 저장하는 변수*/
	boolean isFindButtonClicked = false;
	boolean isNameFindButtonClicked = false;
	
	
	//건물번호
	EditText editBldNum1;
	EditText editBldNum2;
	
	
	//지하여부
	Spinner spinUnderground;
	ButtonView btnUnderground;
	boolean addrIsUnderground = false;
	
	
	//건물명
	EditTextView editBldName1;
	EditTextView editBldName2;
	EditText editBldDong;
	EditText editBldFloor;
	EditText editBldHo;
	
	
	//검색버튼
	Button btnCancel;
	Button btnFindStart;
	
	String[] initials = {"ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"};
	String[] initialsValue = {"가","까","나","다","따","라","마","바","빠","사","싸","아","자","짜","차","카","타","파","하",""};
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.popTheme);
		setContentView(R.layout.cmm_mob_new_addr_insert);
		
		init();
		//parseAddress();
	}
	
	
	//기존에 입력된 주소가 있으면 가져옴
/*	public void parseAddress() {
		try {
	//		Intent transedIntent = getIntent();
			//String addr = transedIntent.getStringExtra("ADDRESS");
//			if (addr.length() > 2) {
//				String[] addrs = addr.split(" ");
//				
//				int pos = 0;
//				for (String data : arrDataset) {
//					if (addrs[1].equals(data)) spinSi.setSelection(pos);
//					pos++;
//				}
//			}
		} catch (Exception e) {
			e.getMessage();
		}
	}*/
	
	
	
	//위젯 초기화
	public void init() {
		//타이틀뷰
		titleView = (TitleView)findViewById(R.id.title_Cn);
		titleView.setTitle(getBaseContext().getString(R.string.addr_new_title));
		titleView.setBackgroundImage(R.drawable.titlebarsub);
		
		if (!INPUT_YN) {
			findViewById(R.id.input_layout).setVisibility(View.GONE);
		}
		
		editSi = (EditText)findViewById(R.id.edit_NewAddr_Si);
//		editSi.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				spinSi.performClick();
//			}
//		});
		btnSiFind = (Button)findViewById(R.id.btn_NewAddr_Si_Find);
		btnSiFind.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if (editSi.length() < 2) {
					Toaster.showMsg(getBaseContext(), "검색할 시군구 명을 입력하세요.");
				} else {
					hideKeyboard(editRoadname);
					
					final String keyword = editSi.getText().toString();
					
					if (keyword.contains(" ") && !keyword.matches(".* ")) {
						final String[] divs = keyword.split(" ");
						if (divs[1].matches(".*시") || divs[1].matches(".*군") || divs[1].matches(".*구")) {
							AlertDialog.Builder dlg = new AlertDialog.Builder(CmmMobNewAddrInsert.this);
							dlg.setTitle("검색 방법");
							dlg.setMessage("검색방법을 선택하세요 :");
							dlg.setNegativeButton("'"+divs[1]+"'로 검색", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									getDatas(itemsSi, keyword,"cgg");
//									listDist.show();
								}
							});
							dlg.setPositiveButton("'"+divs[0]+" "+divs[1]+"'로 검색", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									getDatas(itemsSi, divs[1],"cgg");
//									listDist.show();
								}
							});
							dlg.show();
						}
					} else {
						getDatas(itemsSi, keyword,"cgg");
//						listDist.show();
					}
				}
			}
		});
		
		
		//시군구 검색 리스트
		listDist = (AddressDistrictListView)findViewById(R.id.addrList_NewAddr_District);
		listDist.initiate(itemsSi);
		listDist.notifyDataSetChanged();
		listDist.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				hiddenSi = listDist.getItem1(position);
				hiddenGu = listDist.getItem2(position);
				sidoData = tmpSi.get(position-1);
				editSi.setText(hiddenSi + " " + hiddenGu);
				listDist.gone();
			}
		});
		ScrollView scrollRoot = (ScrollView)findViewById(R.id.scroll_NewAddr_View);
		listDist.setTouchIntercepter(scrollRoot);
		
		
		//도로명 - 검색 타입
		btnKeywordGroup = (RadioGroup)findViewById(R.id.btn_NewAddr_Keyword_Type);
		btnKeywordGroup.setOnCheckedChangeListener(this);
		
		
		//검색 항목
		spinInitials = (Spinner)findViewById(R.id.spin_NewAddr_Initials);
		final ArrayAdapter<String> initialAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item, initials);
		spinInitials.setAdapter(initialAdapter);
		spinInitials.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if (initialSelected) {
					String selectedInitial = parent.getItemAtPosition(position).toString();
					btnKeywordInitial.setText(selectedInitial);
					
					hideKeyboard(editRoadname);
					getDatas(itemsInitial, position+"","in");
				}
				initialSelected = true;
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});
		
		textKeywordType = (TextAlignView)findViewById(R.id.text_NewAddr_Keyword);
		
		btnKeywordInitial = (ButtonView)findViewById(R.id.edit_NewAddr_Keyword_Initial);
		btnKeywordInitial.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (editSi.getText().toString().indexOf(" ") > -1) spinInitials.performClick();
				else Toaster.showMsg(CmmMobNewAddrInsert.this, R.string.addr_msg_value_sigungufind_null);
			}
		});
		
		editRoadname = (EditTextView)findViewById(R.id.edit_NewAddr_Keyword);
//		InputFilter[] FilterArray = new InputFilter[1];
//		FilterArray[0] = new InputFilter.LengthFilter(1);
//		editKeyword.setFilters(FilterArray);
		
		btnKeywordFind = (Button)findViewById(R.id.btn_NewAddr_Keyword);
		btnKeywordFind.setOnClickListener(this);
		
		editFullAddress = (EditText)findViewById(R.id.edit_NewAddr_FullAddr);
		
		//초성검색
		listDistForNewAddr = (NewAddressDistrictListView)findViewById(R.id.addrList_NewAddr_Keyword);
		listDistForNewAddr.initiate(itemsInitial);
		listDistForNewAddr.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				if (sidoData != null) {
					btnKeywordInitial.setText(listDistForNewAddr.getItem1(position));
					editRoadname.setText(listDistForNewAddr.getItem2(position));
					umdData = tmpUmd.get(position-1);
					listDistForNewAddr.gone();
				}else {
					Toaster.showMsg(CmmMobNewAddrInsert.this, "시군구 선택이 되지 않았습니다 시군구를 먼저 선택해주세요.");
				}
			}
		});
		listDistForNewAddr.setTouchIntercepter(scrollRoot);
		
		
		//건물번호
		editBldNum1 = (EditText) findViewById(R.id.edit_NewAddr_BldNum1);
		editBldNum2 = (EditText) findViewById(R.id.edit_NewAddr_BldNum2);
		
		/* 건물번호 관련 이벤트 수정 필요 */
		
		
		//지하여부
		spinUnderground = (Spinner)findViewById(R.id.spin_NewAddr_underground);
		final String[] undergroundItems = {"지상","지하","공중"};
		ArrayAdapter<String> adapterUnderground = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item, undergroundItems);
		spinUnderground.setAdapter(adapterUnderground);
		spinUnderground.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				btnUnderground.setText(undergroundItems[position]);
				if (addressNew == null) {
					addressNew = new Address();
				}
				addressNew.setaddrIsUnder(undergroundItems[position]);
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				btnUnderground.setText(parent.getItemAtPosition(0).toString());
				addrIsUnderground = false;
			}
		});
		
		btnUnderground = (ButtonView)findViewById(R.id.btn_NewAddr_Underground);
		btnUnderground.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				spinUnderground.performClick();
			}
		});
		
		
		//비필수항목
		editBldName1 = (EditTextView)findViewById(R.id.edit_NewAddr_BldName);
		editBldName2 = (EditTextView)findViewById(R.id.edit_NewAddr_BldName2);
		editBldDong = (EditText)findViewById(R.id.edit_NewAddr_BldDong);
		editBldFloor = (EditText)findViewById(R.id.edit_NewAddr_BldFloor);
		editBldHo = (EditText)findViewById(R.id.edit_NewAddr_BldHo);
		
		
		//검색버튼
		btnCancel = (Button)findViewById(R.id.btn_NewAddr_Cancel);
		btnCancel.setOnClickListener(this);
		btnFindStart = (Button)findViewById(R.id.btn_NewAddr_FindStart);
		btnFindStart.setOnClickListener(this);
		
		
		//기본 상태 설정
		setKeywordSearchingType(0);
	}
	
	//시군구 데이터를 받아오는 메소드
	public void getDatas(final ArrayList<ArrayList<String>> items, String keyword,final String gbn) {
		"cgg".equals(gbn);
		items.clear();
		Binding param = new Binding();
		
		
		String[] servletArr;
		if ("cgg".equals(gbn)){
			String siSrch = editSi.getText().toString();
			param.put("rdn_cgg_nm", siSrch);
			servletArr = cggServlet;
		}else {
			param.put("rdn_cgg_code",sidoData.get("regn_code").substring(0, 5));
			param.put("rdn_nm", editRoadname.getText().toString());
			if (!"road".equals(gbn)) {
				param.put("rdn_nm_st", initialsValue[Integer.parseInt(keyword)]);
				param.put("rdn_nm_ed", initialsValue[Integer.parseInt(keyword)+1]);
			}
			servletArr = umdServlet;
		}
		
		CmmMobServletHandler handler = new CmmMobServletHandler(CmmMobNewAddrInsert.this);
		CmmMobServlet servlet = new CmmMobServlet(CmmMobNewAddrInsert.this, 
				servletArr[0],servletArr[1],servletArr[2], 
				handler.getHandler(new HttpResult() {
					@Override
					public void httpCallback(DataSet data) {
						// TODO Auto-generated method stub
						ArrayList<Hashtable<String, String>> tmp = data.getHashData();
						for (int j = 0; j < tmp.size(); j++) {
							ArrayList<String> distItem = new ArrayList<String>();
							if ("cgg".equals(gbn)) {
								tmpSi = data.getHashData();
								//regn_code 에서 앞에 5자리를 짜른것이 rdn_cgg_code
								distItem.add(tmpSi.get(j).get("rdn_sido_nm"));
								distItem.add(tmpSi.get(j).get("rdn_cgg_nm"));
								itemsSi.add(distItem);
								listDist.show();
							}else {
								tmpUmd = data.getHashData();
								distItem.add(tmpUmd.get(j).get("rdn_nm"));
								distItem.add(tmpUmd.get(j).get("rdn_umd_nm"));
								itemsInitial.add(distItem);
								listDistForNewAddr.show();
							}
							
						}
					}
				}), param);
		servlet.start();
	}
	
	public String makeFullAddress() {
		StringBuilder builder = new StringBuilder();
		
		builder.append(editSi.getText().toString()+" ");
		builder.append(editRoadname.getText().toString()+" ");
		builder.append(editBldNum1.getText().toString());
		if (!editBldNum2.getText().toString().equals("")) builder.append("-"+editBldNum2.getText().toString());
		
		return builder.toString();
	}
	
	
	
	//입력된 필드의 값들을 주소 개체에 저장한다
	public void saveDatasToAddress() {
		if (addressNew == null) {
			addressNew = new Address();
		}
		addressNew.setRegn_code(sidoData.get("regn_code"));
		addressNew.setRdn_sido_nm(sidoData.get("rdn_sido_nm"));
		addressNew.setRdn_cgg_code(sidoData.get("rdn_cgg_nm"));
		
		addressNew.setRdn_nm(umdData.get("rdn_nm"));
		addressNew.setRdn_code(umdData.get("rdn_code"));
		addressNew.setRdn_umd_gbn(umdData.get("rdn_umd_gbn"));
		addressNew.setRdn_umd_no(umdData.get("rdn_umd_no"));
		addressNew.setRdn_umd_code(umdData.get("rdn_umd_code"));
		addressNew.setRdn_umd_nm(umdData.get("rdn_umd_nm"));
		addressNew.setaddrBldNum1(editBldNum1.getText().toString());
		addressNew.setaddrBldNum2(editBldNum2.getText().toString());
		addressNew.setaddrIsUnder(spinUnderground.getSelectedItem().toString());
		addressNew.setaddrSiGunGu(editSi.getText().toString());
		addressNew.setaddrRoadname(editRoadname.getText().toString());
		addressNew.setaddrBldNum1(editBldNum1.getText().toString());
		addressNew.setaddrBldNum2(editBldNum2.getText().toString());
		addressNew.setaddrBldName1(editBldName1.getText().toString());
		addressNew.setaddrBldName2(editBldName2.getText().toString());
		addressNew.setaddrBldDong(editBldDong.getText().toString());
		addressNew.setaddrBldHo(editBldHo.getText().toString());
		addressNew.setIs_srch_jibun("N");
	}
	
	
	
	@Override
	public void onBackPressed() {
		mAddrOverAll = "";
		finishStep(false);
	}
	
	
	
	//닫힐 때 주소를 리턴
	public void finishStep(boolean hasChanged) {
		if (hasChanged) {
			Intent reIntent = new Intent();
			reIntent.putExtra("ADDRESS", mAddrOverAll);
			saveDatasToAddress();
			reIntent.putExtra("data", addressNew);
			setResult(RESULT_OK, reIntent);
		}
		else setResult(RESULT_CANCELED);
		finish();
	}
	
	
	
	//도로명 키워드 검색 방법 선택 버튼
	boolean isModeInitial = true;
	final static int KEYWORD_SEARCH_INITIAL = 0x10;
	final static int KEYWORD_SEARCH_NAME = 0x20;
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.btn_NewAddr_Keyword_Initial :
			isModeInitial = true;
			setKeywordSearchingType(KEYWORD_SEARCH_INITIAL);
			break;
			
		case R.id.btn_NewAddr_Keyword_Name :
			isModeInitial = false;
			setKeywordSearchingType(KEYWORD_SEARCH_NAME);
			break;
		default:
			break;
		}
		
//		editKeyword.setText("");
	}
	
	//초성검색-명칭검색 방법 변경 메소드
	public void setKeywordSearchingType(int type) {
		switch (type) {
		case KEYWORD_SEARCH_INITIAL :
			btnKeywordInitial.setVisibility(View.VISIBLE);
			editRoadname.setVisibility(View.GONE);
			btnKeywordFind.setVisibility(View.GONE);
			
			textKeywordType.setText("초성검색");
			break;
			
			
		case KEYWORD_SEARCH_NAME : default :
//			editKeyword.setHint("도로명");
			editRoadname.setVisibility(View.VISIBLE);
			btnKeywordInitial.setVisibility(View.GONE);
			btnKeywordFind.setVisibility(View.VISIBLE);
//			
//			initialSelected = false;
//			InputFilter[] FilterArray = new InputFilter[1];
//			FilterArray[0] = new InputFilter.LengthFilter(100);
//			editKeyword.setFilters(FilterArray);
			
			textKeywordType.setText("명칭검색");
			break;
		}
	}
	
	//버튼
	@Override
	public void onClick(View button) {
		switch (button.getId()) {
		//입력 버튼
		case R.id.btn_NewAddr_FindStart :
			mAddrOverAll = makeFullAddress();
			
			//건물번호가 비었을 때
			if (editBldNum1.getText().toString().equals("")) {
				Toaster.showMsg(this, R.string.addr_msg_value_bldnum_null);
			}
			
			//도로명이 선택되지 않은 초기 상황일 때
//			else if (!isFindButtonClicked) {
//				Toaster.showMsg(this, R.string.addr_msg_value_roadnum_null);
//			}
			
			//조건 OK
			else {
				finishStep(true);
			}
			break;
			
			
		//취소 버튼
		case R.id.btn_NewAddr_Cancel :
			mAddrOverAll = "";
			finishStep(false);
			break;
		//키워드 검색 버튼
		case R.id.btn_NewAddr_Keyword :
			isFindButtonClicked = true;
			//올바른 값인지 확인
			if (editRoadname.length() == 0)
				Toaster.showMsg(this, R.string.addr_msg_value_null);
			else {
				if (editSi.getText().toString().length() > 0 && editSi.getText().toString().indexOf(" ")>0) {
					getDatas(itemsInitial, editRoadname.getText().toString(), "road");
					//키보드 숨김
					hideKeyboard(editRoadname);
					listDistForNewAddr.show();
				}
			}
			break;
		default :
			break;
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case CmmMobServletHandler.PROGRESS_DIALOG:
			return ProgressDialog.show(CmmMobNewAddrInsert.this, "", "로딩중입니다.",false,true);
		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	//키보드 숨김
	public void hideKeyboard(View focusView) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
	}
}
























